<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>
    Javascript Audio Processing
  </title>
  <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js?autoload=true&amp;skin=sunburst&amp;lang=css" defer="defer"></script>
  <style type="text/css">
    body {
			font-family:Arial, Helvetica, sans-serif;
		}
    .prettyprint ol.linenums>li {
      list-style-type: decimal
    }
  </style>
</head>
<body>

  <h1> FFT Analysis </h1>
  <p id="funcs"></p>
  <p>
		The Fast Fourrier Transform analysis.
  </p>
  <p>
    You might need to clear the cache to make sure your latest worklet processor code is loading.
  </p>

  <button id="playButton">Play</button>
  <button id="stopButton">Stop</button>
  <button id="plusButton">+</button>
  <button id="minusButton">–</button>
  <button id="loadSampleButton">Load</button>
  <script type="module">
    // NOTE: We don't need to conflate the WASM with utils for loading samples, so we segregate them from post.js
    // import Module from '../build/maximilian.wasmmodule.js';
    // import {
    //   loadSampleToArray
    // } from '../build/maximilian.wasmmodule.js';
    import {
      loadSampleToArray
    } from '../../common/maximilian.util.js';

    window.loadSampleToArray = loadSampleToArray; 
  </script>
  <script type="text/javascript">
    let audioContext;
    let audioWorkletNode;
    let customProcessorName = 'maxi-processor';
    let workletUrl = 'maxi-processor.js';

    class MaxiNode extends AudioWorkletNode {

      constructor(audioContext, processorName) {
        super(audioContext, processorName);
      }
    }

    function setButtonEventHandlers() {
      const playButton = document.getElementById('playButton');
      playButton.addEventListener("click", () => playAudio());
      const stopButton = document.getElementById('stopButton');
      stopButton.addEventListener("click", () => stopAudio());
      const plusButton = document.getElementById('plusButton');
      plusButton.addEventListener("click", () => increaseVolume());
      const minusButton = document.getElementById('minusButton');
      minusButton.addEventListener("click", () => decreaseVolume());
      const loadSampleButton = document.getElementById('loadSampleButton');
      loadSampleButton.addEventListener("click", () => loadSample());
    }

    function playAudio() {

      if(audioContext === undefined)
        audioContext = new AudioContext();

      try {
        audioContext.audioWorklet.addModule(workletUrl).then(() => {
          stopAudio();
          audioWorkletNode = new MaxiNode(audioContext, customProcessorName);

          audioWorkletNode.port.onmessage = (event) => {
            //  data from the processor.
            console.log("from processor: " + event.data);
          };

          audioWorkletNode.connect(audioContext.destination);
        }).catch((e => console.log("Error on loading worklet: ", e)));
      } catch (err) {
        console.log("AudioWorklet not supported in this browser: ", err.message);
      }
    }

    function sendAudioArray(sampleWorkletObjectName, float32Array) {
      if (float32Array !== undefined && audioWorkletNode !== undefined) {
        // console.log('f32array: ' + float32Array);
        audioWorkletNode.port.postMessage({
          [sampleWorkletObjectName]: float32Array,
        });
      }
    }

    function loadSample() {
      if (audioContext !== undefined) {
        loadSampleToArray(audioContext, "beat", "beat2.wav", sendAudioArray);

      } else throw "Audio Context is not initialised!";
    }

    function stopAudio() {
      if (audioWorkletNode !== undefined) {
        audioWorkletNode.disconnect(audioContext.destination);
        audioWorkletNode = undefined;
      }
    }

    function increaseVolume() {
      if (audioWorkletNode !== undefined) {
        const gainParam = audioWorkletNode.parameters.get('gain');
        gainParam.value += 0.01;
      }
    }

    function decreaseVolume() {
      if (audioWorkletNode !== undefined) {
        const gainParam = audioWorkletNode.parameters.get('gain');
        gainParam.value -= 0.01;
      }
    }

    document.addEventListener("DOMContentLoaded", () => {
      setButtonEventHandlers();
    });
  </script>
</body>
</html>
